/*
 * 首页主组件 - Home Page Component
 * 包含网站首页的所有功能：英雄区域、文章列表、侧边栏等
 */
import React, { useEffect, useState } from 'react';
import { useNavigate } from 'umi';
import IiiuHomeTitle from '../../components/iiiuHomeTitle';
import FadeInCard from '../../components/FadeInCard';
import TypewriterText from '../../components/TypewriterText';
import CategoryTags from '../../components/CategoryTags';
import SidebarTags from '../../components/SidebarTags';
import styles from './home.less';

// 引入图片资源
// import picImage from '../../assets/images/pic.png';
const picImage = 'https://iiiu-assets-images.oss-cn-beijing.aliyuncs.com/assets/cardimage.jpg?Expires=1756339685&OSSAccessKeyId=TMP.3KtH5yADB6FBiLcodsY4PjZoRWiHAp7TX3bJSF8tsyY5b4bSveBbwYfjfMZyPLJJAWvoxb23EJfkPnsemai1fjLjnEWYF7&Signature=UXbsah3xXvy1LNF5Y53t8jc6A6o%3D';

// 引入服务端API
import { getPostPage, getPostIdsByCategoryId } from '../../services/Post/api';
import { getAllCategory } from '@/services/Category/api';
import { getAdminInfo } from '@/services/User/api';

// 使用从models导入的Post接口定义
import { Category } from '@/models/category';
import { Post } from '../../models/post';
import { ApiResponse } from '@/models/common';



const Home: React.FC = () => {
  const navigate = useNavigate();
  const [scrollY, setScrollY] = useState(0);

  useEffect(() => {
    const handleScroll = () => {
      setScrollY(window.scrollY);
    };

    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);


  // 添加文章列表状态管理
  const [posts, setPosts] = useState<Post[]>([]);
  const [filteredPosts, setFilteredPosts] = useState<Post[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // 添加分类列表状态管理
  const [categoryList, setCategoryList] = useState<Category[]>([]);
  const [selectedCategoryId, setSelectedCategoryId] = useState<number | null>(null);




  useEffect(() => {

    const fetchPosts = async () => {
      try {
        setLoading(true);
        const result = await getPostPage(1, 8);

        // 正确处理ApiResponse包装的分页数据
        if (result.success && result.data?.records) {
          setPosts(result.data.records);
          setFilteredPosts(result.data.records);
        } else {
          setError('获取文章列表失败');
        }
      } catch (error) {
        console.error('获取文章列表错误:', error);
        setError('获取文章列表失败，请稍后重试');
      } finally {
        setLoading(false);
      }
    };

    const fetchCategoryList = async () => {
      try {
        const categoriesResponse = await getAllCategory();

        // 正确处理ApiResponse包装的数据
        if (categoriesResponse.success && categoriesResponse.data) {
          setCategoryList(categoriesResponse.data);
        } else {
          setError('获取分类列表失败');
        }
      } catch (error) {
        console.error('获取分类列表错误:', error);
        setError('获取分类列表失败，请稍后重试');
      }
    };



    fetchPosts();
    fetchCategoryList();

  }, []);

  // 处理分类选择
  const handleCategorySelect = async (categoryId: number | null) => {
    setSelectedCategoryId(categoryId);
    setLoading(true);
    
    try {
      if (categoryId === null) {
        // 如果选择"全部"，显示所有文章
        setFilteredPosts(posts);
      } else {
        // 根据分类ID获取文章
        const categoryPosts = await getPostIdsByCategoryId(categoryId);
        
        if (categoryPosts) {
          setFilteredPosts(categoryPosts);
        } else {
          setError('获取分类文章失败');
          // 如果API调用失败，回退到本地过滤
          const filtered = posts.filter(post => post.categoryId === categoryId);
          setFilteredPosts(filtered);
        }
      }
    } catch (error) {
      console.error('获取分类文章错误:', error);
      setError('获取分类文章失败，请稍后重试');
      // 如果API调用失败，回退到本地过滤
      if (categoryId !== null) {
        const filtered = posts.filter(post => post.categoryId === categoryId);
        setFilteredPosts(filtered);
      }
    } finally {
      setLoading(false);
    }
  };


  // 计算背景模糊程度
  const blurAmount = Math.min(scrollY / 10, 10);

  return (
    <div className={styles.homePage}>
      {/* Hero Section */}
      <section className={styles.heroSection}>
        {/* 背景图片 - 注释掉的代码供后续替换 */}
        {/*
        <div 
          className={styles.heroBackground}
          style={{
            backgroundImage: 'url("/path/to/your/background-image.jpg")',
            filter: `blur(${blurAmount}px)`,
          }}
        />
        */}
        <div
          className={styles.heroBackground}
          style={{
            filter: `blur(${blurAmount}px)`,
          }}
        />
        <div className={styles.heroContent}>
          <IiiuHomeTitle
            text="iiiuHomePic"
            fontSize={80}
            duration={3000}
          />
          <div className={styles.subtitle}>
            <TypewriterText
              text="分享技术 · 记录生活 · 探索未知"
              speed={150}
              delay={4000}
            />
          </div>
        </div>
      </section>

      {/* Content Section */}
      <section className={styles.contentSection}>
        <div className={styles.container}>
          {/* Main Content Area */}
          <div className={styles.mainContent}>
            {/* Articles Section */}
            <section className={styles.articlesSection}>

              {/* <div className={styles.categoryGrid}>
                <div className={styles.categoryCard}>
                  <div className={styles.categoryIcon}>📝</div>
                  <div className={styles.categoryContent}>
                    <h3>技术文章</h3>
                    <p>分享前端、后端技术心得</p>
                  </div>
                </div>
                <div className={styles.categoryCard}>
                  <div className={styles.categoryIcon}>💡</div>
                  <div className={styles.categoryContent}>
                    <h3>学习笔记</h3>
                    <p>记录学习过程和思考</p>
                  </div>
                </div>
                <div className={styles.categoryCard}>
                  <div className={styles.categoryIcon}>🚀</div>
                  <div className={styles.categoryContent}>
                    <h3>项目实战</h3>
                    <p>实际项目开发经验</p>
                  </div>
                </div>
                <div className={styles.categoryCard}>
                  <div className={styles.categoryIcon}>🌟</div>
                  <div className={styles.categoryContent}>
                    <h3>生活随笔</h3>
                    <p>记录生活点滴和感悟</p>
                  </div>
                </div>
              </div> */}
              


              {/* 分类标签 */}
              <div className={styles.categoryTagsContainer}>
                <CategoryTags 
                  categories={categoryList} 
                  onCategorySelect={handleCategorySelect} 
                />
              </div>

              <div className={styles.cardGrid}>
                {filteredPosts.length > 0 ? (
                  filteredPosts.map((item, index) => (
                    <FadeInCard
                      key={item.id}
                      title={item.title}
                      abstractInfo={item.abstractInfo}
                      image={picImage}
                      delay={index * 200}
                      onClick={() => navigate(`/post/${item.id}`)}
                    />
                  ))
                ) : (
                  selectedCategoryId !== null && !loading && (
                    <div className={styles.emptyState}>
                      <div className={styles.emptyEmoji}></div>
                      <div className={styles.emptyText}>该分类下面没有文章</div>
                    </div>
                  )
                )}
              </div>
            </section>

            {/* Sidebar */}
            <aside className={styles.sidebar}>
              <SidebarTags />
            </aside>
          </div>
        </div>
      </section>
    </div>
  );
};

export default Home;
